package edu.misaka.moe.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;

public class DBConnection {
	private static Logger log = Logger.getLogger(DBConnection.class);

	private static ThreadLocal<Connection> connections = new ThreadLocal<>();
	private static final String DRIVER_CLASS_NAME;
	private static final String URL;
	private static final String NAME;
	private static final String PASSWORD;
	static {
		Properties prop = new Properties();
		try {
			prop.load(DBConnection.class.getResourceAsStream("/jdbc.properties"));
		} catch (IOException e) {
			log.error("jdbc.properties file not found,the exception is:" + e.getLocalizedMessage());
		}
		DRIVER_CLASS_NAME = prop.getProperty("jdbc.driverClassName");
		URL = prop.getProperty("jdbc.url");
		NAME = prop.getProperty("jdbc.name");
		PASSWORD = prop.getProperty("jdbc.password");
		try {
			Class.forName(DRIVER_CLASS_NAME);
		} catch (ClassNotFoundException e) {
			log.error("class not found,the exception is:" + e.getLocalizedMessage());
		}
	}

	public static Connection getConnection() {
		Connection conn = connections.get();
		try {
			if (conn == null || conn.isClosed()) {
				conn = DriverManager.getConnection(URL, NAME, PASSWORD);
				log.debug("open connection success...");
				connections.set(conn);

			}
		} catch (SQLException e) {
			log.error("database connection error,the exception is:" + e.getLocalizedMessage());
		}
		log.debug("get connection...");
		return conn;
	}

	public static void closeConnection(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
				log.debug("close connection success...");
			} catch (SQLException e) {
				log.error("database close error,the exception is:" + e.getLocalizedMessage());
			}
		}

	}
}
